package com.basksoft.baskreport.demo.service;


import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import com.basksoft.report.core.definition.datasource.DatasourceDefinition;
import com.basksoft.report.core.model.datasource.BuildinDatasourceProvider;
import com.basksoft.report.core.model.datasource.DatasourceWrapper;

public class SampleCenterDatasource implements BuildinDatasourceProvider {
	private static Properties properties = new Properties();

	/* 读取Properties文件
	static {   
		InputStream in = Object.class.getResourceAsStream("/jdbc.properties");   
		try {   
			properties.load(in);  
		} catch (IOException e) {   
			e.printStackTrace();   
		}   
    }   
	 */
	@Override
	public DataSource buildDatasource(DatasourceDefinition def) {
		// 从命令行读取配置参数，便于docker部署
		DataSource dataSource = null;
		properties.put("username", System.getProperty("dbserver.user"));
		properties.put("password", System.getProperty("dbserver.pwd"));
		properties.put("driverClassName", "com.mysql.cj.jdbc.Driver");
		properties
                .put("url",
                        "jdbc:mysql://"+System.getProperty("dbserver.host")+":"+System.getProperty("dbserver.port")+"/baskreportsample?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true");
		//读取Properties文件
		// InputStream in = Object.class.getResourceAsStream("/jdbc.properties");   
		// try {   
		// 	properties.load(in);  
		// } catch (IOException e) {   
		// 	e.printStackTrace();   
		// }   
		
		try {
			dataSource = BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return dataSource;
	}

	@Override
	public void destroyDatasource(DatasourceWrapper ds) {
		if (ds == null)
			return;
		DataSource datasource = ds.getDatasource();
		if (datasource instanceof BasicDataSource) {
			BasicDataSource basicDatasource = (BasicDataSource) datasource;
			try {
				basicDatasource.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}
